package com.ezbuy.common.helper;

import org.junit.Test;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailHelper {

    @Test
    public void test() throws MessagingException {
        String host = "smtp.gmail.com";
        String from = "yutianran666@gmail.com";
        String pass = "qbrxisocuovqfoep";
        String[] to = {"yutianran666+test@foxmail.com"};
        send(host, from, pass, to);
        System.out.println("发送邮件完成");
    }

    public static void send(String host, String from, String pass, String[] to) throws MessagingException {
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // 在本行添加
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");


        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        InternetAddress[] toAddress = new InternetAddress[to.length];

        // 获取地址的array
        for (int i = 0; i < to.length; i++) { // 从while循环更改而成
            toAddress[i] = new InternetAddress(to[i]);
        }
        for (int i = 0; i < toAddress.length; i++) { // 从while循环更改而成
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }
        message.setSubject("sending in a group");
        message.setText("Welcome to JavaMail");
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
}
